<template>
  <div class="myAutocomplete">
    <el-autocomplete
      class="el-form-item_all_input"
      popper-class="myAutocomplete-popper"
      v-model.lazy="childModel"
      :ref="autocompleteRef"
      :fetch-suggestions="querySearch"
      :disabled="disabled"
      :placeholder="
        disabled || configDefault.readonly ? '' : configDefault.placeholderLabel
      "
      :trigger-on-focus="configDefault.triggerOnFocus"
      :hide-loading="configDefault.hideLoading"
      :readonly="configDefault.readonly"
      :value-key="configDefault.props.id"
      @focus="focus"
      @change="autocompleteChange(childModel)"
      @select="autocompleteSelect(childModel)"
    >
      <!--有相关slot插槽-->
      <template :slot="configDefault.slotType">{{
        configDefault.slotName
      }}</template>
    </el-autocomplete>
  </div>
</template>

<script>
import { getComboData } from "@/components/api/fromSource.js";
import XEUtils from "xe-utils";
export default {
  name: "myAutocomplete",
  props: {
    //自定义按钮ref
    autocompleteRef: {
      type: String,
      default() {
        return "vueAutocomplete";
      },
    },
    model: {
      // 当前组件绑定值
      type: [String, Number, Boolean, Array, Object],
      require: true,
    },
    modelKey: {
      //当前绑定值key，可以用于formData中获取到当前组件渲染配置items
      type: String,
      default() {
        return "";
      },
    },
    fromSource: {
      //用于formData中获取到当前组件渲染配置items
      type: [Array, String],
      default() {
        return "";
      },
    },
    which: {
      //第几组自动完成框
      type: [String, Number],
      default() {
        return 1;
      },
    },
    disabled: {
      // 当前组件是否禁用
      type: Boolean,
      default() {
        return false;
      },
    },
    config: {
      //私有配置数据
      type: [String, Object],
      require: true,
    },
    formConfigData: {
      //配置数据
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      childModel: this.model ? this.model : "",
      configDefault: {
        isCustomData: true,//是否自定义数据
        options: [],//建议数据
        readonly: false, // 是否只读
        slotType: "", // 当前组件slot插槽类型prefix（输入框头部内容）、suffix（输入框尾部内容）、prepend（输入框前置内容）、append（输入框后置内容）
        triggerOnFocus: true,
        hideLoading: false,
        props: {
          // 当前选项配置 {label:'显示文本值',id:'当前选项绑定值'}
          label: "label",
          id: "id",
        },
        placeholderLabel: "",//默认显示文本
      },
    };
  },
  watch: {
    childModel(val, oldVal) {
      if (val !== oldVal) {
        this.$emit("update:model", val);
      }
    },
    model(val, oldVal) {
      if (val !== this.childModel) {
        this.childModel = val;
      }
    },
    formConfigData: {
      handler(newVal) {
        let formConfigObj = newVal
          ? newVal[this.fromSource] || newVal[this.modelKey]
          : {};
        let publicConfigObj = newVal ? newVal["publicAttr"] : {};
        let cfg =
          this.config && XEUtils.isString(this.config)
            ? XEUtils.toStringJSON(this.config)
            : this.config || {};
        this.configDefault = XEUtils.merge(
          this.configDefault,
          publicConfigObj,
          cfg,
          formConfigObj
        );
      },
      deep: true,
      immediate: true,
    },
  },
  created() {},
  mounted() {
    this.getData();
  },
  methods: {
    getData() {
      if (!this.configDefault.isCustomData) {
        let params = { elementCode: this.fromSource || this.modelKey };
        getComboData(params).then((res) => {
          this.initAutoCompleteData(res.data);
        });
      }
    },
    // 当input获得焦点时触发
    focus() {},
    initAutoCompleteData(data) {
      this.configDefault.options = data && data.length > 0 ? data : [];
    },
    querySearch(queryString, cb) {
      var restaurants = this.configDefault.options
        ? this.configDefault.options
        : [];
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (childModel) => {
        const valKey = this.configDefault.props.id;
        console.log("valKey",valKey,childModel[valKey])
        return (
          childModel[valKey] &&
          childModel[valKey].toLowerCase() &&
          childModel[valKey]
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) !== -1
        );
      };
    },
    autocompleteSelect(newVal) {
      this.$emit("selectCallback", this.modelKey + "_" + this.which, newVal);
    },
    autocompleteChange: function (newVal) {
      // 当前组件change改变方法
      this.$emit("changeCallback", this.modelKey + "_" + this.which, newVal);
    },
  },
};
</script>

<style  lang="less" scoped>
.myAutocomplete-popper {
  .el-autocomplete-suggestion__wrap {
    overflow: scroll;
    li {
      line-height: normal;
      padding-top: 7px;
      padding-bottom: 7px;
    }
  }
}
</style>
